﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using org.pdfbox.pdfparser;
using org.pdfbox.pdmodel;
using org.pdfbox.util;
using System.IO;
using System.Configuration;

using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Index;
using Lucene.Net.Documents;
//using org.apache.lucene.analysis;
//using org.apache.lucene.analysis.standard;
//using org.apache.lucene.index;
//using org.apache.lucene.document;
//https://lucenepdf.googlecode.com/svn/trunk/
//k2q9p2a3


namespace PdfLucene
{
    public partial class CreandoIndice : Form
    {

        public static int costoProgressParaAgregarAIndice = 2;
        private string directorio;
        private LuceneIndexer index= null;
        int noProcesados;

        public CreandoIndice()
        {
            InitializeComponent();
        }

 


        private string ReadTextFromPdf(string filePath)
        {
            string text="";
            java.io.File input = new java.io.File(filePath);
            PDDocument doc = PDDocument.load(input);
            if (doc.isEncrypted())
                text = "";
            else{
                PDFTextStripper stripper = new PDFTextStripper();
                text =  stripper.getText(doc);
            }

            if (doc != null){
                doc.close();
            }
            return text;

        }


        private void Form1_Load(object sender, EventArgs e)
        {

        }



        public void EmpezarConstruirIndice(string directorio, LuceneIndexer index)
        {
            this.directorio = directorio;
            this.index = index;
            ultraProgressBar1.Minimum = 0;
            ultraProgressBar1.Maximum = DirectoryManager.GetPDFFromDirectory(directorio).Length + costoProgressParaAgregarAIndice;
            ultraProgressBar1.Step = 1;
            ultraProgressBar1.Value = 0;
            label2.Visible = false;
            ultraButton1.Visible = false;

            label1.Text = "";
            backgroundWorker1.RunWorkerAsync();
            this.ShowDialog();
        }




        private void Salir()
        {
            //CloseIndex();
            this.Dispose();
        }


        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

            string[] files = DirectoryManager.GetPDFFromDirectory(directorio);

            List<PDFFile> pdfFiles = new List<PDFFile>();

            noProcesados = 0;

            if (files != null)
            {
                for (int i = 0; i < files.Length; i++)
                {

                    FileInfo fileInfo = new FileInfo(files[i]);
                    backgroundWorker1.ReportProgress(i / (files.Length + costoProgressParaAgregarAIndice), System.IO.Path.GetFileName(files[i]));
                    try
                    {
                        PDFFile pdf = PDFManager.GetFileContents(fileInfo);
                        pdfFiles.Add(pdf);
                    }
                    catch (ApplicationException ex)
                    {
                        noProcesados++;
                        System.Console.WriteLine(string.Format("Número de archivos con error:{0}",noProcesados));
                        //POr si se quiere desplegar en algun lugar los pdf que no se pudieron leer
                    }
                    if (noProcesados > 0)
                    {
                        backgroundWorker1.ReportProgress(i / (files.Length + costoProgressParaAgregarAIndice), "@3");
                    }


                }
            }

            backgroundWorker1.ReportProgress(files.Length / (files.Length+costoProgressParaAgregarAIndice), "@2");
            index.CreateNewIndexFile();
            index.IndexDocuments(pdfFiles);
            index.CloseIndex();
            System.Threading.Thread.Sleep(2000);

        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if ((e.UserState as string) == "@2")
            {
                ultraStatusBar1.Text = "Agregando pdf's a indice...";
            }
            else
            {
                if ((e.UserState as string) == "@3")
                    label1.Text = noProcesados + " pdfs no pueden ser procesados";
                else
                {
                    string filename = e.UserState as string;
                    ultraStatusBar1.Text = "Procesando archivo '" + filename + "' ...";
                }
            }
            ultraStatusBar1.Refresh();

            ultraProgressBar1.PerformStep();
            ultraProgressBar1.Refresh();

        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            label2.Visible = true;
            ultraProgressBar1.Value = ultraProgressBar1.Maximum;
            ultraStatusBar1.Text= "Se ha termido de procesar todos los archivos y construir el indice!!!. Presione 'salir' para terminar";
            ultraStatusBar1.Refresh();
            ultraButton1.Visible = true;

        }

        private void ultraButton1_Click(object sender, EventArgs e)
        {
            Salir();
        }


    }
}
